package fun.hijklmn.magic.admin.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import fun.hijklmn.magic.admin.common.enums.UserStatusEnum;
import fun.hijklmn.magic.admin.common.pojo.Role;
import fun.hijklmn.magic.admin.common.pojo.User;
import fun.hijklmn.magic.admin.common.pojo.UserRole;
import fun.hijklmn.magic.admin.server.pojo.SysUser;
import fun.hijklmn.magic.admin.server.service.RoleService;
import fun.hijklmn.magic.admin.server.service.UserRoleService;
import fun.hijklmn.magic.admin.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Description
 * @Author fs
 * @Date 2021/6/25 18:15
 * @Version 0.0.1-SNAPSHOT
 **/
@Slf4j
@Service
@Primary
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("is_delete", 0);
        queryWrapper.apply(String.format(" (e_mail = '%s' or cellphone = '%s' or e_mail = '%s' or user_name='%s') ", s, s, s, s));
        queryWrapper.last("limit 1");
        User user = userService.getOne(queryWrapper);

        if (user == null) {
            throw new UsernameNotFoundException("用户未注册");
        }

        if (UserStatusEnum.freeze.status().intValue() == user.getStatus()) {
            throw new LockedException("账号被冻结");
        }

        if (UserStatusEnum.expire.status().intValue() == user.getStatus()) {
            throw new AccountExpiredException("账号已过期");
        }

        QueryWrapper<UserRole> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("is_delete", 0);
        queryWrapper1.eq("user_id", user.getId());
        queryWrapper1.last("limit 1");

        UserRole userRole = userRoleService.getOne(queryWrapper1);
        if (userRole == null) {
            throw new UsernameNotFoundException("该账号无法使用，没有分配角色");
        }

        Role role = roleService.getById(userRole.getRoleId());
        if (role == null || role.getIsDelete()) {
            throw new UsernameNotFoundException("该账号无法使用，没有分配角色");
        }

        return new SysUser(user, role);

    }

}
